﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Bainx.WPF.Extend
{
    /// <summary>
    /// WPF跨线程调用
    /// </summary>
    public static class WPFControlExtensions
    {
        /// <summary>
        /// 跨线程执行方法
        /// </summary>
        /// <param name="ctl">表示与 System.Windows.Threading.Dispatcher 关联的对象。</param>
        /// <param name="doit">封装一个方法，该方法不具有参数并且不返回值。</param>
        /// <param name="priority">描述可通过 System.Windows.Threading.Dispatcher 调用操作的优先级。</param>
        public static void InvokeIfNeeded(
                                this System.Windows.Threading.DispatcherObject ctl,
                                Action doit,
                                System.Windows.Threading.DispatcherPriority priority)
        {
            if (System.Threading.Thread.CurrentThread != ctl.Dispatcher.Thread)
            {
                ctl.Dispatcher.Invoke(priority,doit);
            }
            else
            {
                doit();
            }
        }
        /// <summary>
        /// 跨线程执行方法
        /// </summary>
        /// <typeparam name="T">参数类型</typeparam>
        /// <param name="ctl">表示与 System.Windows.Threading.Dispatcher 关联的对象。</param>
        /// <param name="doit">封装一个方法，该方法不具有参数并且不返回值。</param>
        /// <param name="args">参数</param>
        /// <param name="priority">描述可通过 System.Windows.Threading.Dispatcher 调用操作的优先级。</param>
        public static void InvokeIfNeeded<T>(
                                this System.Windows.Threading.DispatcherObject ctl,
                                Action<T> doit,
                                T args,
                                System.Windows.Threading.DispatcherPriority priority)
        {
            if (System.Threading.Thread.CurrentThread != ctl.Dispatcher.Thread)
            {                
                ctl.Dispatcher.Invoke(priority,
                doit, args);
            }
            else
            {
                doit(args);
            }
        }
    }
}
